package com.github.interview.http;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;

import java.io.Serializable;

/**
 * http请求返回的结果对象
 * @param <T> 泛型对象
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> implements Serializable {

    private static final long serialVersionUID = -4696898674758059398L;


    private int status;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String message;


    public static <T> Result<T> failed(HttpStatus httpStatus) {
        Result<T> result = new Result<>();
        result.setStatus(httpStatus.value());
        result.setMessage(httpStatus.getReasonPhrase());
        result.setData(null);
        return result;
    }

    public static <T> Result<T> failed(BusinessException exception) {
        Result<T> result = new Result<>();
        result.setStatus(exception.getStatus());
        result.setMessage(exception.getMessage());
        result.setData(null);
        return result;
    }

    public static <T> Result<T> success(T t) {
        Result<T> result = new Result<>();
        result.setStatus(HttpStatus.OK.value());
        result.setMessage(HttpStatus.OK.getReasonPhrase());
        result.setData(t);
        return result;
    }

}
